<?php
/**
 * Created by IntelliJ IDEA.
 * User: TinND
 * Date: 4/2/14
 * Time: 1:57 PM
 */
/* soak in the passed variable or set our own */
include 'connection.php';

	$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : -1; //-1 is no limit
	$format = strtolower($_GET['format']) == 'xml' ? 'xml' : 'json'; //json is the default

	/* grab the posts from the db */
	$query = "SELECT * FROM Product";
	if($number_of_posts != -1)
	    $query = $query." LIMIT $number_of_posts";

	$result = mysql_query($query,$link) or die('Errant query:  '.$query);

	/* create one master array of the records */
	$posts = array();
	if(mysql_num_rows($result)) {
		while($post = mysql_fetch_assoc($result)) {
			$posts[] = $post;
		}
	}

	/* output in necessary format */
	if($format == 'json') {
		header('Content-type: application/json');
		echo json_encode(array('posts'=>$posts));
	} else {
		header('Content-type: text/xml');
		echo '<posts>';
		foreach($posts as $index => $post) {
			if(is_array($post)) {
				foreach($post as $key => $value) {
					echo '<',$key,'>';
					if(is_array($value)) {
						foreach($value as $tag => $val) {
							echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
						}
					}
					echo '</',$key,'>';
				}
			}
		}
		echo '</posts>';
	}

	/* disconnect from the db */
	@mysql_close($link);